//
//  PlayVoiceSubtitleView.m
//  GC_OC
//
//  Created by 曾霄逸 on 2022/3/21.
//

#import "PlayVoiceSubtitleView.h"
#import "PlayVoiceSubitleTableViewCell.h"
#import "WPFLyricView.h"
#import "WPFLyricParser.h"
#import "WPFLyric.h"
#import "NSDateFormatter+shared.h"
@interface PlayVoiceSubtitleView()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong)NSString* url;
@property (nonatomic, strong)NSString* fileidStr;
@property (nonatomic, strong)NSMutableArray* beginTimeSubArr;
@property (nonatomic, strong)NSMutableArray* endtimeArray;
@property (nonatomic, strong)NSMutableArray* subtitleArr;
@property (nonatomic, strong)UITableView*    tableview;
//歌词
@property (strong, nonatomic) WPFLyricView *lyricView;
@property (nonatomic,strong) NSArray *lyrics;
@property (nonatomic,assign) NSInteger currentLyricIndex;

@end

@implementation PlayVoiceSubtitleView
-(instancetype)initWithFrame:(CGRect)frame
{
    self=[super initWithFrame:frame];
    if(self)
    {
        self.beginTimeSubArr=[NSMutableArray new];
        self.endtimeArray=[NSMutableArray new];
        self.subtitleArr=[NSMutableArray new];
        self.lyricView = [[WPFLyricView alloc] initWithFrame:frame];
        self.lyricView.backgroundColor =  [[UIColor whiteColor]colorWithAlphaComponent:0.0f];
        [self addSubview:_lyricView];
        [self initView];
    }
    return self;
}
-(void)initView
{
   
//    _tableview=[[UITableView alloc]initWithFrame:CGRectMake(0,0,self.width,self.height) style:UITableViewStylePlain];
//    _tableview.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];
//    _tableview.dataSource=self;
//    _tableview.delegate=self;
//    [_tableview registerNib:[UINib nibWithNibName:@"PlayVoiceSubitleTableViewCell" bundle:nil] forCellReuseIdentifier:@"PlayVoiceSubitleTableViewCell"];
//    //设置背景颜色
//    _tableview.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:0.0f];
//    //删除分割线
//    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
//    [self addSubview:_tableview];
}
- (void)refreshUI:(CGRect)frame{
    self.lyricView.frame = frame;
    self.lyricView.vScrollerView.frame  = frame;
}
- (void)updateLyric {
    
    WPFLyric *lyric = self.lyrics[self.currentLyricIndex];
    WPFLyric *nextLyric = nil;
    if (self.currentLyricIndex >= self.lyrics.count - 1) {
        nextLyric = [[WPFLyric alloc] init];
        nextLyric.time = [ICMusicPlayManager sharedManager].totalTime;
    }else{
        nextLyric = self.lyrics[self.currentLyricIndex + 1];;
    }


    if ([ICMusicPlayManager sharedManager].currentTime < lyric.time && self.currentLyricIndex > 0) {
        self.currentLyricIndex --;
        [self updateLyric];
    }else if([ICMusicPlayManager sharedManager].currentTime >= nextLyric.time && self.currentLyricIndex < self.lyrics.count - 1){
        self.currentLyricIndex ++;
        [self updateLyric];
    }
//    // 设置歌词内容
//    [self.lyricsLabel setValue:lyric.content forKey:@"text"];
//
//    // 设置歌词颜色
    CGFloat progress = ([ICMusicPlayManager sharedManager].currentTime - lyric.time) / (nextLyric.time - lyric.time);
//    [self.lyricsLabel setValue:@(progress) forKey:@"progress"];
//
    self.lyricView.currentLyricIndex = self.currentLyricIndex;

    self.lyricView.lyricProgress = progress;
}
- (void)updateProgress {
    if (self.lyrics.count > 0) {
        
        [self updateLyric];
    }
    
//    // 更新锁屏界面
//    if (isLocked && isScreenBright) {
//        [self updateLockScreen];
//    }
}
#pragma mark - tableview delegate and datasource
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return hig(70);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _subtitleArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PlayVoiceSubitleTableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:@"PlayVoiceSubitleTableViewCell"];
    //取消点击效果
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    [cell initCell:self.subtitleArr[indexPath.row]];
    cell.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:0.0f];
    return cell;
}
-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
-(void)refreshUrl:(NSString*)url andFileId:(NSString*)fileidStr
{
    if ([NSString stringWithFormat:@"%@", url].length < 10) {
        return;
    }
//    [self.beginTimeSubArr removeAllObjects];
//    [self.endtimeArray removeAllObjects];
//    [self.subtitleArr removeAllObjects];
//    [self.tableview reloadData];
    self.url=url;
    self.fileidStr=fileidStr;
    [self getData];    
}
-(void)getData
{
//    NSArray* paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
//    NSString* fullName=[NSString stringWithFormat:@"%@.text",self.fileidStr];
    
    NSArray* paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString* fullName=[NSString stringWithFormat:@"%@.lrc",self.fileidStr];
    NSString* theFilePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:fullName];
    NSFileManager* fileManager=[NSFileManager defaultManager];
    
    if([fileManager fileExistsAtPath:theFilePath])
    {
        NSString* str=[NSString stringWithContentsOfFile:theFilePath encoding:NSUTF8StringEncoding error:nil];
        [self conversionAction:str];
        NSLog(@"str====%@",str);
    }else
    {
        NSString* pathStr=[self.url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSURLRequest* request=[NSURLRequest requestWithURL:[NSURL URLWithString:pathStr]];
        NSURLSession* session=[NSURLSession sharedSession];
        NSURLSessionDataTask* dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
           if(!error)
           {
               NSString* string=[[NSMutableString alloc]initWithData:data encoding:NSUTF8StringEncoding];
               [self conversionAction:string];
               [self saveString:string andFileName:self.fileidStr];
           }
        }];
        [dataTask resume];
    }
}
-(void)conversionAction:(NSString*)string
{
    NSArray* singlearray=[string componentsSeparatedByString:@"\n"];
    NSMutableArray* begintimeArray1=[NSMutableArray new];
    NSMutableArray* endtimeArray1=[NSMutableArray new];
    NSMutableArray* subtitlesarray1=[NSMutableArray new];
    NSMutableArray *lyricsMutArr = [NSMutableArray array];
    NSString* subStr=@"";
    for(int i=0;i<singlearray.count;i++)
    {
        WPFLyric *lyric = [[WPFLyric alloc] init];
        NSString* subString=singlearray[i];
        NSScanner* scan=[NSScanner scannerWithString:subString];
        NSInteger val;
        if([scan scanInteger:&val] && [scan isAtEnd])
        {
//            NSString* subString=singlearray[i+2];
            subStr=[NSString stringWithFormat:@"%@",[singlearray objectAtIndex:i+2]];
            [subtitlesarray1 addObject:subStr];
            lyric.content =  subStr;
            subStr=@"";
            
            NSString* timeStr=[singlearray objectAtIndex:i+1];
            NSRange range2=[timeStr rangeOfString:@" --> "];
            if(range2.location != NSNotFound)
            {
                NSString* beginstr=[timeStr substringToIndex:range2.location];
                NSString* endStr=[timeStr substringFromIndex:range2.location+range2.length];
                NSArray* arr=[beginstr componentsSeparatedByString:@":"];
                NSArray* arr1=[arr[2] componentsSeparatedByString:@","];
//                float teim=[arr[0] floatValue]*60*60+[arr1[1] floatValue]*60+[arr1[0] floatValue]+[arr1[1] floatValue]/1000;
                NSDateFormatter *formatter = [NSDateFormatter sharedDateFormatter];
                formatter.dateFormat = @"hh:mm:ss,SS";
                NSDate *timeDate = [formatter dateFromString:beginstr];
                NSDate *initDate = [formatter dateFromString:@"00:00:00,00"];
                NSTimeInterval teim  = [timeDate timeIntervalSinceDate:initDate];
                lyric.time = teim;
                
                NSNumber* beginnum=[NSNumber numberWithFloat:teim];
                [begintimeArray1 addObject:beginnum];
                
                NSArray* array=[endStr componentsSeparatedByString:@":"];
                NSArray* arr2=[array[2] componentsSeparatedByString:@","];
                float fl=[array[0] floatValue]*60*60+[array[1] floatValue]*60+[arr2[0] floatValue]+[arr2[1] floatValue]/1000;
                NSNumber* endnum=[NSNumber numberWithFloat:fl];
                [endtimeArray1 addObject:endnum];
                [lyricsMutArr addObject:lyric];
            }
        }else
        {
            continue;
        }
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"我加载了%@",self.subtitleArr);
        [self.beginTimeSubArr addObjectsFromArray:begintimeArray1];
        [self.endtimeArray addObjectsFromArray:endtimeArray1];
        [self.subtitleArr addObjectsFromArray:subtitlesarray1];
        [self refreshHeight];
        self.lyrics = [NSArray arrayWithArray:lyricsMutArr];
//        [self.tableview reloadData];
        // 给竖直歌词赋值
        self.lyricView.lyrics = self.lyrics;
    });
}
-(void)refreshHeight
{
    
}
-(void)saveString:(NSString*)string andFileName:(NSString*)fileName
{
    dispatch_async(dispatch_get_global_queue(0,0), ^{
        NSArray* paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString* fullName=[NSString stringWithFormat:@"%@.text",fileName];
        NSString* theFilePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:fullName];
        NSFileManager* fileManager=[NSFileManager defaultManager];
        if(![fileManager fileExistsAtPath:theFilePath])
        {
            [@"" writeToFile:theFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
        }
        NSFileHandle* fileHandle=[NSFileHandle fileHandleForUpdatingAtPath:theFilePath];
        [fileHandle seekToEndOfFile];
        NSData* stringData=[[NSString stringWithFormat:@"%@\n",string]dataUsingEncoding:NSUTF8StringEncoding];
        [fileHandle writeData:stringData];
        [fileHandle closeFile];
    });    
}
-(void)clearData
{
    [self.beginTimeSubArr removeAllObjects];
    [self.endtimeArray removeAllObjects];
    [self.subtitleArr removeAllObjects];
    [self.tableview reloadData];
}

//- (WPFLyricView *)lyricView{
//
//    if(!_lyricView)
//    {
//        _lyricView=[[WPFLyricView alloc]init];
//        [self.view addSubview:_lyricView];
//    }
//    return _lyricView;
//}
@end
